#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
订单解析模块 - 从共享文件夹路径中解析订单信息
"""

import os
import re
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from PyQt6.QtCore import QObject, pyqtSignal


class OrderInfo:
    """订单信息类"""
    
    def __init__(self, path: str, number: str = "", customer: str = ""):
        self.path = path
        self.number = number
        self.customer = customer
        self.is_valid = bool(number and customer)
        
    def __repr__(self):
        return f"OrderInfo(number={self.number}, customer={self.customer})"
        
    def to_dict(self):
        """转换为字典格式"""
        return {
            'path': self.path,
            'number': self.number,
            'customer': self.customer,
            'is_valid': self.is_valid
        }


class OrderParser(QObject):
    """订单解析器"""
    
    # 信号定义
    orders_parsed = pyqtSignal(list)  # 订单解析完成信号
    parse_error = pyqtSignal(str)     # 解析错误信号
    
    def __init__(self):
        super().__init__()
        self.base_path = ""
        self.date_suffix = ""
        
    def set_base_path(self, path: str, date: str = ""):
        """设置基础路径和日期后缀"""
        self.base_path = path
        self.date_suffix = date
        
    def parse_orders_from_folder(self, folder_path: str = None) -> List[OrderInfo]:
        """从文件夹中解析订单信息"""
        if folder_path is None:
            folder_path = self.base_path
            
        if not folder_path or not os.path.exists(folder_path):
            self.parse_error.emit(f"路径不存在: {folder_path}")
            return []
            
        orders = []
        
        try:
            # 扫描文件夹中的所有子目录
            for item in os.listdir(folder_path):
                item_path = os.path.join(folder_path, item)
                
                if os.path.isdir(item_path):
                    # 解析子目录名称
                    order_info = self._parse_folder_name(item, item_path)
                    if order_info and order_info.is_valid:
                        orders.append(order_info)
                        
        except Exception as e:
            self.parse_error.emit(f"解析文件夹失败: {str(e)}")
            
        # 发送解析完成信号
        self.orders_parsed.emit(orders)
        return orders
        
    def _parse_folder_name(self, folder_name: str, full_path: str) -> Optional[OrderInfo]:
        """解析文件夹名称，提取订单信息"""
        try:
            # 使用正则表达式匹配格式: "编号_客户名称"
            # 例如: "101_上海勇灵"
            
            # 格式1: "编号_客户名称"
            pattern1 = r'^(\d+)_(.+)$'
            match1 = re.match(pattern1, folder_name)
            
            if match1:
                number = match1.group(1)
                customer = match1.group(2)
                
                return OrderInfo(full_path, number, customer)
            
            # 格式2: 纯数字开头
            pattern2 = r'^(\d+)(.*)$'
            match2 = re.match(pattern2, folder_name)
            
            if match2:
                number = match2.group(1)
                remaining = match2.group(2).strip('_')
                
                if remaining:
                    customer = remaining
                else:
                    # 如果只有数字，尝试从子目录获取客户名称
                    customer = self._extract_customer_from_subdir(full_path)
                
                return OrderInfo(full_path, number, customer)
                
        except Exception as e:
            print(f"解析文件夹名称失败 {folder_name}: {e}")
            
        return None
        
    def _extract_customer_from_subdir(self, folder_path: str) -> str:
        """从子目录中提取客户名称"""
        customer = ""
        
        try:
            if not os.path.exists(folder_path):
                return customer
                
            items = os.listdir(folder_path)
            
            for item in items:
                item_path = os.path.join(folder_path, item)
                
                if os.path.isdir(item_path):
                    # 如果子目录名包含中文，可能是客户名称
                    if re.search(r'[\u4e00-\u9fff]', item):
                        customer = item
                        break
                        
        except Exception as e:
            print(f"从子目录提取客户名称失败 {folder_path}: {e}")
            
        return customer
        
    def parse_single_path(self, path: str) -> Optional[OrderInfo]:
        """解析单个路径"""
        if not path or not os.path.exists(path):
            return None
            
        # 获取路径的最后一部分作为文件夹名
        folder_name = os.path.basename(path)
        return self._parse_folder_name(folder_name, path)
        
    def get_orders_from_paths(self, paths: List[str]) -> List[OrderInfo]:
        """从多个路径中获取订单信息"""
        orders = []
        
        for path in paths:
            order_info = self.parse_single_path(path)
            if order_info and order_info.is_valid:
                orders.append(order_info)
                
        return orders
        
    def validate_order_info(self, order_info: OrderInfo) -> bool:
        """验证订单信息是否完整"""
        return (order_info.number and 
                order_info.customer and
                order_info.number.isdigit())
                
    def format_order_display(self, order_info: OrderInfo) -> str:
        """格式化订单显示信息"""
        if not order_info.is_valid:
            return f"无效订单: {order_info.path}"
            
        return f"编号: {order_info.number} | 客户: {order_info.customer}"
        
    def export_orders_to_dict(self, orders: List[OrderInfo]) -> List[Dict]:
        """导出订单信息为字典列表"""
        return [order.to_dict() for order in orders if order.is_valid]
        
    def filter_orders_by_customer(self, orders: List[OrderInfo], customer: str) -> List[OrderInfo]:
        """按客户名称筛选订单"""
        if not customer or customer == "全部客户":
            return orders
            
        return [order for order in orders if customer in order.customer]
        
    def filter_orders_by_number(self, orders: List[OrderInfo], number: str) -> List[OrderInfo]:
        """按编号筛选订单"""
        if not number:
            return orders
            
        return [order for order in orders if order.number == number]
        
    def sort_orders(self, orders: List[OrderInfo], sort_by: str = "number") -> List[OrderInfo]:
        """排序订单"""
        if sort_by == "number":
            return sorted(orders, key=lambda x: int(x.number) if x.number.isdigit() else 0)
        elif sort_by == "customer":
            return sorted(orders, key=lambda x: x.customer)
        else:
            return orders


class OrderPathBuilder:
    """订单路径构建器"""
    
    @staticmethod
    def build_order_path(base_path: str, date_suffix: str, number: str, customer: str) -> str:
        """构建订单路径"""
        # 格式: base_path/date_suffix/number_customer
        folder_name = f"{number}_{customer}"
        return os.path.join(base_path, date_suffix, folder_name)
        
    @staticmethod
    def build_folder_name(number: str, customer: str) -> str:
        """构建文件夹名称"""
        return f"{number}_{customer}"
        
    @staticmethod
    def parse_existing_path(path: str) -> Dict[str, str]:
        """解析现有路径，提取各个组件"""
        result = {
            'base_path': '',
            'date_suffix': '',
            'number': '',
            'customer': ''
        }
        
        try:
            path_parts = Path(path).parts
            
            if len(path_parts) >= 2:
                result['base_path'] = str(Path(*path_parts[:-2]))
                result['date_suffix'] = path_parts[-2]
                
                # 解析文件夹名称
                folder_name = path_parts[-1]
                pattern = r'^(\d+)_(.+)$'
                match = re.match(pattern, folder_name)
                
                if match:
                    result['number'] = match.group(1)
                    result['customer'] = match.group(2)
                    
        except Exception as e:
            print(f"解析路径失败 {path}: {e}")
            
        return result
